package com.esreport.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esreport.Utils.GuavaCacheUtil;
import com.esreport.Utils.HttpSessionUtils;
import com.esreport.dto.ArticleInformation;
import com.esreport.service.OtherSourceService;
import com.esreport.service.XOtherSourceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * OtherSourceServiceImpl
 *
 * @author cexy
 * @description:
 * @date 2019/5/28
 * @time 14:43
 */
@Slf4j
@Service
public class XOtherSourceServiceImpl implements XOtherSourceService {

    @Autowired
    private OtherSourceService otherSourceService;

    @Value("${ucenter.url}")
    public String ucenterURL;
    @Value("${conf.url}")
    public String confURL;
    @Value("${rec.url}")
    public String recURL;
    @Value("${dangjian.url}")
    public String dangjianURL;

    private static CloseableHttpClient client = HttpSessionUtils.buildHttpClient();

    @Override
    public Integer countUser(String siteId) {
        Map<String, String> param = new HashMap<>();
        param.put("method", "userCount");
        param.put("siteId", siteId);
        String jsonStr;
        try {
            jsonStr = HttpSessionUtils.httpPost(client, ucenterURL, param);
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        JSONObject json = JSON.parseObject(jsonStr);
        //System.out.println(json.toJSONString());
        int code = json.getInteger("code");
        if (code != 0) {
            return -1;
        }
        return json.getInteger("data");
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<ArticleInformation> getTopArticle(Integer siteId, Integer num, String startTime, String endTime) throws IOException, ParseException {
        List<ArticleInformation> tops = (List<ArticleInformation>) GuavaCacheUtil.get("tops_" + siteId + "_" + num + startTime + "_" + endTime);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (tops == null || tops.size() == 0) {
            List<ArticleInformation> list = new ArrayList<>();
            String cmsJson;
            JSONArray cmsArray;
            JSONArray recArray;
            String cmsURL = otherSourceService.getCmsUrl(siteId);

            Map<String, String> cmsParam = new HashMap<>();
            cmsParam.put("method", "getArticleByTops");
            cmsParam.put("startTime", startTime);
            cmsParam.put("endTime", endTime);
            cmsParam.put("siteId", siteId.toString());
            cmsParam.put("num", num.toString());
            cmsJson = HttpSessionUtils.httpPost(client, cmsURL, cmsParam);
            //log.info(cmsJson);
            cmsArray = JSON.parseArray(cmsJson);
            for (int i = 0; i < cmsArray.size(); i++) {
                ArticleInformation ai = new ArticleInformation();
                JSONObject cmsArticle = (JSONObject) cmsArray.get(i);
                ai.setId(cmsArticle.getInteger("ID"));
                ai.setHitCount(cmsArticle.getInteger("HitCount"));
                ai.setTitle(cmsArticle.getString("Title"));
                ai.setThumb(cmsArticle.getString("Logo"));
                ai.setPublishDate(cmsArticle.getString("PublishDate"));
                list.add(ai);
            }
            /*Map<String, String> recParam = new HashMap<>();
            String method = "/getClickRanking";
            //开始时间结束时间都不为空
            if ((startTime != null && !"".equals(startTime)) && (endTime != null && !"".equals(endTime))) {
                recParam.put("startTime", String.valueOf(sf.parse(startTime).getTime()));
                recParam.put("endTime", String.valueOf(sf.parse(endTime).getTime()));
                method = "/getVideoForTime";
            }
            //结束时间不为空，开始时间为空
            if ((endTime != null && !"".equals(endTime)) && (startTime == null || "".equals(startTime))) {
                recParam.put("endTime", String.valueOf(sf.parse(endTime).getTime()));
                recParam.put("startTime", String.valueOf(sf.parse("1970-01-01 00:00:00").getTime()));
                method = "/getVideoForTime";
            }
            //开始时间不为空，结束时间为空
            if ((startTime != null && !"".equals(startTime)) && (endTime == null || "".equals(endTime))) {
                recParam.put("startTime", String.valueOf(sf.parse(startTime).getTime()));
                recParam.put("endTime", String.valueOf(System.currentTimeMillis()));
                method = "/getVideoForTime";
            }
            recParam.put("siteId", siteId.toString());
            recParam.put("type", "1");
            recParam.put("page", "1");
            recParam.put("number", num.toString());
            String recJson = HttpSessionUtils.httpPost(client, recURL + method, recParam);
            //log.info(recJson);
            JSONObject obj = JSON.parseObject(recJson);
            if (obj.getInteger("code") == 200) {
                recArray = obj.getJSONArray("data");
                for (Object o : recArray) {
                    ArticleInformation ai = new ArticleInformation();
                    JSONObject recArticle = (JSONObject) o;
                    ai.setThumb(recArticle.getString("Logo"));
                    ai.setPublishDate(recArticle.getString("PublishDate"));
                    ai.setTitle(recArticle.getString("Title"));
                    ai.setHitCount(recArticle.getInteger("HitCount"));
                    ai.setId(recArticle.getInteger("ID"));
                    list.add(ai);
                }
            }*/
            Collections.sort(list);
            if (list.size() > num) {
                list = list.subList(0, num);
            }
            tops = list;
            GuavaCacheUtil.put("tops_" + siteId + "_" + num + startTime + "_" + endTime, list);
        }
        return tops;
    }

    @Override
    public Long countDTByUserName(String username) {
        Map<String, String> param = new HashMap<>();
        param.put("username", username);
        try {
            String result = HttpSessionUtils.httpPost(client, dangjianURL+"/countDT", param);
            JSONObject json = JSON.parseObject(result);
            if(json.getString("code").equals("200")){
                JSONObject map = json.getJSONObject("data");
                return map.getLong("dtcount");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    @Override
    public Long countDTBySite(String siteId) {
        Map<String, String> param = new HashMap<>();
        param.put("siteId", siteId);
        try {
            String result = HttpSessionUtils.httpPost(client, dangjianURL+"/countDTBySite", param);
            JSONObject json = JSON.parseObject(result);
            if(json.getString("code").equals("200")){
                JSONObject map = json.getJSONObject("data");
                return map.getLong("dtcount");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    @Override
    public Map<String, Long> countPeopleNumAndZoneNumAndPassTypeRecord(String siteId) {
        Map<String, Long> result = new HashMap<>();
        Map<String, String> param = new HashMap<>();
        param.put("siteId",siteId);
        try {
            String info = HttpSessionUtils.httpPost(client, dangjianURL+"/getStudyAchievements", param);
            JSONObject json = JSON.parseObject(info);
            if(json.getString("code").equals("200")){
                JSONObject map = json.getJSONObject("data");
                result.put("playerCount", map.getLong("playerCount"));
                result.put("zoneCount",map.getLong("zoneCount"));
                result.put("recordCount",map.getLong("recordCount"));
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

//    public static void main(String[] args) {
//        Map<String, Long> result = new HashMap<>();
//        Map<String, String> param = new HashMap<>();
//        param.put("siteId","215");
//        try {
//            String info = HttpSessionUtils.httpPost(client, "http://dangjianapi.i2863.com/statistics/getStudyAchievements", param);
//            JSONObject json = JSON.parseObject(info);
//            if(json.getString("code").equals("200")){
//                JSONObject map = json.getJSONObject("data");
//                result.put("playerCount", map.getLong("playerCount"));
//                result.put("zoneCount",map.getLong("zoneCount"));
//                result.put("recordCount",map.getLong("recordCount"));
//            }
//            System.out.println(json.toJSONString());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}
